package com.excilys.ymca.service.remotefile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.util.Log;

import com.excilys.ymca.model.Contact;
import com.excilys.ymca.service.IContactListService;

public class ContactListServiceRemoteFileImpl implements IContactListService {

	private static final String	TAG	= ContactListServiceRemoteFileImpl.class.getSimpleName();
	private String				fileUrl;

	@Override
	public List<Contact> getContactList() {

		ArrayList<Contact> contacts = new ArrayList<Contact>();

		try {
			URL url = new URL(fileUrl);

			InputStream is = url.openStream();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(is));

				String line;
				while ((line = br.readLine()) != null) {
					StringTokenizer stk = new StringTokenizer(line, "|");
					contacts.add(new Contact(stk.nextToken(), stk.nextToken()));
				}
			} finally {
				if (is != null) {
					is.close();
				}
			}
		} catch (IOException e) {
			Log.e(TAG, "Huhu, something bad happened", e);
		}

		return contacts;
	}

	public void setFileUrl(String fileUrl) {
		this.fileUrl = fileUrl;
	}

}
